var engine = new FacetEngine();

function updateFrequentWordView(c) {
  $.getJSON(
    '-/get-frequent-words?' + $.param(c) + '&limit=500&callback=?',
    null,
    function(r) {
      renderFrequentWordView(r.results, $('#view-container').empty(), function(evt, entry) {
        renderSubview(entry.w, entry.t);
      });
    },
    'jsonp'
  );
}

function renderFrequentWordView(wordEntries, container, click) {
  var table = $('<table><tr><th>count</th><th>POS tag</th><th>word</th></tr></table>')
    .addClass('frequency-table')
    .appendTo(container);
  if (click) {
    table.addClass('clickable');
  }
  table = table[0];
  
  $.each(wordEntries, function(i, entry) {
    var cn = table.rows.length % 2 == 0 ? 'even' : 'odd';
    var tr = table.insertRow(table.rows.length);
    $(tr).addClass(cn);
    if (click) {
      $(tr).click(function(evt) { return click(evt, entry); });
    }
    $(tr.insertCell(tr.cells.length)).addClass('count').text(formatInteger(entry.c));
    $(tr.insertCell(tr.cells.length)).addClass('tag').text(entry.t);
    $(tr.insertCell(tr.cells.length)).addClass('word').text(entry.w);
  });
}

function renderSubview(word, tag) {
  var elmt = $('#subview-container').empty().html(DOM.loadHTML('scripts/frequent-words-subview.html'));
  var elmts = DOM.bind(elmt);
  elmts.word.text(word);
  elmts.tag.text(tag);
  if (tag in POSTags) {
    elmts.tagDescription.text(POSTags[tag].label);
  }
  
  var getRelatedWords = function(command, elmt, click) {
    $.getJSON(
      '-/' + command + '?' + $.param({ word: word, word_tag: tag, limit: 20 }) + '&callback=?',
      null,
      function(r) {
        renderFrequentWordView(r.results, elmt, click);
      },
      'jsonp'
    );
  };
  getRelatedWords('get-preceding-words', elmts.precedingWordContainer, function(evt, entry) {
    renderSampleSentences([ entry.w, word ], [ entry.t, tag ]);
  });
  getRelatedWords('get-following-words', elmts.followingWordContainer, function(evt, entry) {
    renderSampleSentences([ word, entry.w ], [ tag, entry.t ]);
  });
  
  renderSampleSentences([word], [tag]);
}

function renderSampleSentences(words, tags) {
  var elmt = $('#sentence-container').empty().show().html(DOM.loadHTML('scripts/sample-sentences.html'));
  var elmts = DOM.bind(elmt);
  elmts.words.text(words.join(' '));
  
  var offset = 0;
  var showTree = function(entry) {
    var html = '<textarea style="width: 800px; height: 500px; font-family: monospace; font-size: 150%"></textarea>';
    var elmt = Lightbox.show(html);
    elmt.find('textarea')[0].value = entry.tree;
  };
  var getSentences = function() {
    var url;
    if (words.length == 1) {
      url = '-/get-sample-sentences-containing-word?' +
        $.param({ word: words[0], word_tag: tags[0], limit: 10, offset: offset }) + '&callback=?';
    } else {
      url = '-/get-sample-sentences-containing-two-words?' +
        $.param({ word1: words[0], word_tag1: tags[0], word2: words[1], word_tag2: tags[1], limit: 10, offset: offset }) + '&callback=?';
    }
    $.getJSON(
      url,
      null,
      function(r) {
        var container = elmts.sampleSentenceContainer.empty();
        $.each(r.results, function(i, entry) {
          var text = entry.segmented_text;
          for (var i = 0; i < words.length; i++) {
            text = text.replace(words[i], '<span class="highlight">' + words[i] + '</span>')
          }
          var li = $('<li>')
            .html(text)
            .appendTo(container);
          
          $('<a>')
            .addClass('light-link')
            .text('tree')
            .attr('href', 'javascript:{}')
            .click(function() { showTree(entry) })
            .appendTo(li);
          
          $('<a>')
            .addClass('light-link')
            .text('translate')
            .attr('target', '_blank')
            .attr('href', 'http://translate.google.com/?' + $.param({ text: entry.segmented_text }))
            .appendTo(li);
            
          $('<a>')
            .addClass('light-link')
            .text('post')
            .attr('target', '_blank')
            .attr('href', entry.url)
            .appendTo(li);
        })
      },
      'jsonp'
    );
  };
  window.setTimeout(getSentences, 1000);
  
  elmts.sampleLeftButton.click(function() {
    offset = Math.max(0, offset - 10);
    getSentences();
  });
  elmts.sampleRightButton.click(function() {
    offset += 10;
    getSentences();
  });
}

$(function() {
  var wordLengthFacet = new Facet(engine, $('#word-length-facet-container'));
  wordLengthFacet.initialize('Word Length');
  wordLengthFacet.restrict = function(c) {
    if (this._selection.length > 0) {
      var s = $.map(this._selection, function(item) { return item.value; }).join(';');
      return $.extend({ word_length: s }, c);
    }
    return c;
  };
  wordLengthFacet._sortChoices = function(choiceList) {
    choiceList.sort(function(a, b) { return a.value - b.value; });
  };
  wordLengthFacet.update = function(c) {
    $.getJSON(
      '-/get-frequent-word-lengths?' + $.param(c) + '&callback=?',
      null,
      function(r) {
        wordLengthFacet._renderChoices($.map(r.results, function(item) {
          return {
            value: item.l,
            label: item.l + (item.l > 1 ? ' chars' : ' char'),
            count: item.c
          };
        }));
      },
      'jsonp'
    );
  };
  
  var tagFacet = new Facet(engine, $('#tag-facet-container'));
  tagFacet.initialize('POS Tags');
  tagFacet.restrict = function(c) {
    if (this._selection.length > 0) {
      var s = $.map(this._selection, function(item) { return item.value; }).join(';');
      return $.extend({ tag: s }, c);
    }
    return c;
  };
  tagFacet.update = function(c) {
    $.getJSON(
      '-/get-frequent-tags?' + $.param(c) + '&callback=?',
      null,
      function(r) {
        tagFacet._renderChoices($.map(r.results, function(item) {
          return {
            value: item.t,
            label: item.t,
            count: item.c,
            description: (item.t in POSTags) ? POSTags[item.t].label : undefined
          };
        }));
      },
     'jsonp'
    );
  };
  
  engine.addFacet(tagFacet);
  engine.addFacet(wordLengthFacet);
  engine.addView({ update: updateFrequentWordView });
  engine.update();
});